package com.cjk.foundation.job;

import org.quartz.CronScheduleBuilder;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class JobManager{
	
	@Autowired
	private Scheduler scheduler;
	
	public void addJob(Class<? extends Job> jobClass, String name, String group, String cron) throws Exception {
		JobDetail jobDetail = JobBuilder.newJob(jobClass) //
				.withIdentity(name, group) //
				.build();
		
		Trigger trigger = TriggerBuilder.newTrigger() //
				.withIdentity(name, group) //
				.startAt(DateBuilder.futureDate(1, IntervalUnit.SECOND)) //
				.withSchedule(CronScheduleBuilder.cronSchedule(cron)) //
				.startNow() //
				.build();
		
		scheduler.scheduleJob(jobDetail, trigger);
		if (!scheduler.isShutdown()) {
			scheduler.start();
        }
	}

}
